<template>
  <!-- background: #f9f9f9; -->
  <div style="background: #fff; height:100%; min-height: 80vh" v-loading="loading">
    <iframe class="embedIfram" id="newdexIframe" style="min-height: 88vh" frameborder="0"></iframe>
  </div>
</template>

<script>
import { EosModel } from '@/utils/eos/';
import { urlhostName, authorized, getReqUrl } from '@/utils/validate';

export default {
  name: 'otc-eos', // otc eos
  data() {
    return {
      parentUrl: '',
      targetOrigin: '',
      loading: false,
    }
  },
  components: {
  },
  props: {},
  watch: {
    '$store.state.app.theme': function change() {
      const response = {
        language: this.$store.state.app.language, // en / zh-CN / zh-TW / ko
        theme: this.$store.state.app.theme === 'theme-278EDA' ? 'white' : 'dark', // white / dark
        node: this.$store.state.app.nodeChecked,
      }
      this.handleResponseMessage('getConfig', response);
    },
    '$store.state.app.language': function change() {
      const response = {
        language: this.$store.state.app.language, // en / zh-CN / zh-TW / ko
        theme: this.$store.state.app.theme === 'theme-278EDA' ? 'white' : 'dark', // white / dark
        node: this.$store.state.app.nodeChecked,
      }
      this.handleResponseMessage('getConfig', response);
    },
    '$store.state.app.nodeChecked': function change() {
      const response = {
        language: this.$store.state.app.language, // en / zh-CN / zh-TW / ko
        theme: this.$store.state.app.theme === 'theme-278EDA' ? 'white' : 'dark', // white / dark
        node: this.$store.state.app.nodeChecked,
      }
      this.handleResponseMessage('getConfig', response);
    },
    '$store.state.app.scatter.identity': {
      handler: function listen() {
        const scatter = this.$store.state.app.scatter;
        if (scatter.chain !== 'eos') {
          this.$router.push({ name: 'index' })
          return;
        }
        let response = {
          identity: null,
          wallet: 'Scatter',
          chain: 'eos',
        }

        const token = localStorage.getItem('Frontend-Token');
        if (scatter && scatter.identity) {
          response = scatter;
          response.token = token || '';
        }
        this.handleResponseMessage('getAccount', response);
        this.handleCustomerServic();
      },
      deep: true,
    },
  },
  computed: {},
  created() {
    document.title = this.$t(`rout.${this.$route.meta.title}`);
  },
  mounted() {
    if (this.$store.state.app.scatter.chain !== 'eos') {
      this.$router.push({ name: 'index' })
      return;
    }
    this.parentUrl = window.location.origin;
    document.getElementById('app').className = 'embedBackground';
    this.handleMounted();
    // Zendex 配置
    // this.handleZendex();
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleReceiveMessage, false);
    document.getElementById('app').classList.remove('embedBackground');
    document.getElementById('XIANKEFU-BAR').style.display = 'none';
    // document.getElementById('XIANKEFU-PANEL').style.display = 'none';
    document.getElementById('newdexIframe').setAttribute('src', '');
  },
  methods: {
    // otc 客服
    handleCustomerServic() {
      const scatter = this.$store.state.app.scatter;
      if (scatter && scatter.identity && this.$route.name === 'otc') {
        zE('webWidget', 'hide'); // eslint-disable-line
        document.getElementById('XIANKEFU-BAR').style.display = 'block';
        return;
      }
      document.getElementById('XIANKEFU-BAR').style.display = 'none';
      zE('webWidget', 'show'); // eslint-disable-line
    },
    handleZendex() {
      window.zESettings = {
        webWidget: {
          chat: {
            suppress: false
          },
          contactForm: {
            suppress: true
          },
          helpCenter: {
            suppress: true
          },
          talk: {
            suppress: true
          },
          answerBot: {
            suppress: true
          }
        }
      }
      zE('webWidget', 'hide'); // eslint-disable-line
    },
    handleMounted() {
      const self = this;
      this.loading = true;
      const env = process.env.NODE_ENV;
      let src = `https://otc.newdex.${urlhostName()}`
      if (env === 'development') {
        src = `http://${getReqUrl('ip')}:${process.env.VUE_APP_PORT21}`
      }
      this.targetOrigin = src;
      let iframeSrc = `${src}/?embed=eos&origin=${encodeURIComponent(this.parentUrl)}&v=${new Date().getTime()}`;
      if (this.$route.params && this.$route.params.personal) { // 内嵌进入个人中心
        const token = localStorage.getItem('Frontend-Token');
        iframeSrc = `${src}/personal?embed=eos&origin=${encodeURIComponent(this.parentUrl)}&t=${token}&v=${new Date().getTime()}`;
      }
      document.getElementById('newdexIframe').setAttribute('src', iframeSrc);
      window.addEventListener('message', this.handleReceiveMessage, false);
      document.getElementById('newdexIframe').onload = (() => {
        self.loading = false;
        self.handleCustomerServic();
      })
    },
    handleReceiveMessage(event) {
      const storeApp = this.$store.state.app;
      const origin = event.origin || event.originalEvent.origin;
      if (origin !== this.targetOrigin) return;
      const message = JSON.parse(event.data);
      console.log('newdex->action', message); // eslint-disable-line
      switch (message.action) {
        case 'getConfig': {
          const response = {
            language: storeApp.language, // en / zh-CN / zh-TW / ko
            node: storeApp.nodeChecked,
            theme: storeApp.theme === 'theme-278EDA' ? 'white' : 'dark' // white / dark
          }
          this.handleResponseMessage(message.action, response);
          break;
        }
        case 'getAccount': {
          const scatter = this.$store.state.app.scatter;
          const token = localStorage.getItem('Frontend-Token');
          let response = {
            identity: null,
            wallet: 'Scatter',
            chain: 'eos',
          }
          if (scatter && scatter.identity) {
            response = scatter;
            response.token = token || '';
            // if (this.$route.params && this.$route.params.personal) { // 内嵌进入个人中心
            //   response.personal = true;
            // } else {
            //   response.personal = false;
            // }
          }
          this.handleResponseMessage(message.action, response);
          break;
        }
        case 'setHeight': {
          console.log('get Height', message.data.height + 'px'); // eslint-disable-line
          document.getElementById('newdexIframe').style.height = `${parseInt(message.data.height, 0)}px`;
          document.getElementById('newdexIframe').style['min-height'] = `${parseInt(message.data.height, 0)}px`;
          document.documentElement.scrollTop = 0;
          break;
        }
        case 'zendex': {
          // zE('webWidget', 'identify', {
          //   name: 'Akira Kogane',
          //   email: 'akira@voltron.com',
          //   organization: 'Voltron, Inc.'
          // });
          // zE('webWidget', 'open'); // eslint-disable-line
          break;
        }
        case 'walletLogin': {
          this.$emit('listenWalletLogin', true);
          break;
        }
        case 'getArbitrarySignature': {
          this.handleAuthorized();
          break;
        }
        case 'eosTransaction': {
          // const params = message.data;
          EosModel.eosTransactionByEmbed(message, (res) => {
            this.handleResponseMessage(message.action, { res });
          });
          break;
        }
        default:
      }
    },
    // 授权
    handleAuthorized() {
      authorized(this, (code) => {
        const response = {
          code,
          token: localStorage.getItem('Frontend-Token')
        }
        this.handleResponseMessage('getArbitrarySignature', response);
      });
    },
    handleResponseMessage(action, data) {
      const iframe = document.getElementById('newdexIframe');
      const message = { action, data }
      iframe.contentWindow.postMessage(JSON.stringify(message), this.targetOrigin);
    },
  },
}
</script>
<style lang="scss" scoped>
</style>

